package com.lry.service.impl;

import java.util.List;

import com.lry.bean.Role;
import com.lry.bean.RoleEnum;
import com.lry.bean.User;
import com.lry.dao.RoleMapper;
import com.lry.dao.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

/**
 * 
 *
 * @author 李瑞益
 * @date 2019/8/20
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    protected UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.getByName(s);
        List<Role> roleList = roleMapper.listRoleByUserId(user.getId());
        user.setRoleList(roleList);
        return user;
    }

    @Transactional
    public int addUser(User user){
        if (isExist(user)) {
            return 0;
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //设置默认权限
        int j = userMapper.addUser(user);
        int[] roles = new int[]{RoleEnum.GENERAL_USER.getId()};
        int i = roleMapper.addRoles(roles, user.getId());
        if (i != 0 && j != 0) {
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 唯一性检查
     * @param user 用户信息
     * @return true 存在
     */
    public boolean isExist(User user) {
        User byName = userMapper.getByName(user.getName());
        return byName == null ? false:true;
    }
}
